package com.xnfh.common.pop

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.View
import com.lxj.xpopup.core.BottomPopupView
import com.xnfh.common.R
import com.xnfh.common.databinding.PopAddressBinding
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast


/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/27 14:56
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/27 14:56
 * @UpdateRemark: 更新说明
 */
class OpenAddressPop(context: Context) : BottomPopupView(context), View.OnClickListener {

    override fun getImplLayoutId(): Int = R.layout.pop_address
    private var mBind: PopAddressBinding? = null
    private var lonandlat: String? = null
    override fun onCreate() {
        super.onCreate()
        mBind = PopAddressBinding.bind(popupImplView)
        mBind!!.popAddressCancle.setOnClickListener(this)
        mBind!!.popAddressBaidu.setOnClickListener(this)
        mBind!!.popAddressGaode.setOnClickListener(this)
        mBind!!.popAddressTengxun.setOnClickListener(this)
    }

    /**
     * 设置位置
     */
    fun setLonandlat(lonandlat: String?) {
        this.lonandlat = lonandlat
    }

    override fun onClick(v: View?) {
        when (v) {
            mBind?.popAddressBaidu -> {
                if (isAvilible(context, "com.baidu.BaiduMap")) {
                    try {
                        val intent = Intent.getIntent("intent://map/direction?" +
                                "destination=latlng:" + lonandlat?.split(",".toRegex())
                            ?.dropLastWhile { it.isEmpty() }?.toTypedArray()
                            ?.get(1) + "," + lonandlat?.split(",".toRegex())
                            ?.dropLastWhile { it.isEmpty() }
                            ?.toTypedArray()?.get(0) + "|name:我的目的地" +  //终点
                                "&mode=driving&" +  //导航路线方式
                                "&src=appname#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end")
                        context.startActivity(intent) //启动调用

                    } catch (e: Exception) {
                        LogUtil.e("打开百度地图失败：${e}")
                    }
                }else{
                    openApplicationMarket("com.baidu.BaiduMap")
                }
                dismiss()
            }

            mBind?.popAddressGaode -> {
                if(isAvilible(context,"com.autonavi.minimap")){
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.addCategory(Intent.CATEGORY_DEFAULT)
                    //将功能Scheme以URI的方式传入data
                    val uri = Uri.parse(
                        "amapuri://route/plan/?sid=&slat=&slon&sname=&did=&dlat=" + lonandlat!!.split(
                            ",".toRegex()
                        ).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1] + "&dlon=" + lonandlat!!.split(",".toRegex())
                            .dropLastWhile { it.isEmpty() }
                            .toTypedArray()[0] + "&dname=&dev=0&t=0")
                    intent.data = uri
                    //启动该页面即可
                    context.startActivity(intent)
                }else{
                    openApplicationMarket("com.autonavi.minimap")
                }
                dismiss()
            }

            mBind?.popAddressTengxun -> {
                if(isAvilible(context,"com.tencent.map")){
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.addCategory(Intent.CATEGORY_DEFAULT)
                    //将功能Scheme以URI的方式传入data
                    //将功能Scheme以URI的方式传入data
                    val uri = Uri.parse(
                        "qqmap://map/routeplan?type=drive&to=我的目的地&tocoord=" + lonandlat!!.split(
                            ",".toRegex()
                        ).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1] + "," + lonandlat!!.split(",".toRegex())
                            .dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                    )
                    intent.data = uri
                    if (intent.resolveActivity(context.packageManager) != null) {
                        //启动该页面即可
                        context.startActivity(intent)
                    }
                }else{
                    openApplicationMarket("com.tencent.map")
                }
                dismiss()
            }

            mBind?.popAddressCancle -> {
                dismiss()
            }
        }
    }

    /**
     * 检查手机上是否安装了指定的packageName的软件
     *
     * @param context
     * @param packageName 应用包名
     * @return
     */
    fun isAvilible(context: Context?, packageName: String): Boolean {
        //获取packagemanager
        val packageManager = context?.packageManager
        //获取所有已安装程序的包信息
        val packageInfos = packageManager?.getInstalledPackages(0)
        //用于存储所有已安装程序的包名
        val packageNames: MutableList<String> = ArrayList()
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (i in packageInfos.indices) {
                val packName = packageInfos[i].packageName
                packageNames.add(packName)
            }
        }
        //判断packageNames中是否有目标程序的包名
        return packageNames.contains(packageName)
    }


    /**
     * 通过包名 在应用商店打开应用
     *
     * @param packageName 包名
     */
    private fun openApplicationMarket(packageName: String) {
        try {
            val str = "market://details?id=$packageName"
            val localIntent = Intent(Intent.ACTION_VIEW)
            localIntent.data = Uri.parse(str)
            context.startActivity(localIntent)
        } catch (e: java.lang.Exception) {
            // 打开应用商店失败 可能是手机没有安装应用市场
            e.printStackTrace()
            TipsToast.showTips(com.xnfh.framework.R.string.open_shop_error)
            // 调用系统浏览器进入商城
            val url = "http://app.mi.com/detail/163525?ref=search"
            openLinkBySystem(url)
        }
    }

    /**
     * 调用系统浏览器打开网页
     *
     * @param url 地址
     */
    private fun openLinkBySystem(url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(url)
        context.startActivity(intent)
    }

}